<template>
  <div class="default-main ba-table-box">
    <el-alert class="ba-table-alert"
              v-if="baTable.table.remark"
              :title="baTable.table.remark"
              type="info"
              show-icon />

    <!-- 表格顶部菜单 -->
    <TableHeader :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
                 :quick-search-placeholder="t('Quick search placeholder', { fields: t('order.order.order_id') })">
      <!-- <template #default>
                <el-button v-blur :disabled="true" class="table-header-operate" type="success">
                    <Icon color="#ffffff" name="el-icon-RefreshRight" />
                    <span class="table-header-operate-text">还原</span>
                </el-button>
            </template> -->
      <template #shop>
        <el-select filterable
                   v-model="baTable.comSearch.form['shop_id']"
                   clearable>
          <el-option v-for="item in shop_arr"
                     :key="item.shop_id"
                     :label="item.shop_name"
                     :value="item.shop_id">
          </el-option>
        </el-select>
      </template>
      <template #orderId>
        <el-input v-model="baTable.comSearch.form['order_id']"
                  :rows="2"
                  type="textarea"
                  placeholder="请输入订单号" />
      </template>
    </TableHeader>

    <template style="display: block;">
      <el-row style="margin:10px 0"
              :gutter="10">
        <el-col :span="3"
                v-if="baTable.auth('automaticShipping')">
          <el-select v-model="state.overseas_warehouse"
                     clearable
                     placeholder="请选择海外仓"
                     @change="overseasWarehouseChange">
            <el-option v-for="item in state.overseas_warehouse_arr"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
              <span style="float: left">{{ item.label || '' }}</span>
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="3"
                v-if="baTable.auth('automaticShipping')">
          <el-select v-model="state.golden_ant"
                     clearable
                     placeholder="请选择顺丰渠道">
            <el-option v-for="item in state.golden_ant_channel"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
              <span style="float: left">{{ item.label }}</span>
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="1.5"
                v-if="baTable.auth('automaticShipping')">
          <el-button type="primary"
                     @click="automaticShippingOperate">自动发货</el-button>
        </el-col>
        <el-col :span="1.5"
                v-if="baTable.auth('mandatoryShipping')">
          <el-button type="primary"
                     @click="mandatoryShippingOperate">强制发货</el-button>
        </el-col>
        <el-col :span="1.5"
                v-if="baTable.auth('export')">
          <el-button type="warning"
                     @click="exportExcelOperate"
                     :loading="state.buttonLoading">
            <Icon :color="'#ffffff'"
                  name="el-icon-Position" />导出
          </el-button>
        </el-col>
        <el-col :span="1.5"
                v-if="baTable.auth('processedShunfeng')">
          <el-button type="danger"
                     @click="processedShunfengOperate">
            <Icon :color="'#ffffff'"
                  name="el-icon-CirclePlusFilled" />标记顺丰TK面单
          </el-button>
        </el-col>
        <el-col :span="1.5"
                v-if="baTable.auth('uploadBrushOrder')">
          <el-upload ref="upload"
                     class="upload-demo"
                     action=""
                     :show-file-list="false"
                     @change="onBrushOrderUpload"
                     :auto-upload="false">
            <template #trigger>
              <el-button type="primary">上传刷单表格</el-button>
            </template>
            <el-link style="color: #ffffff;"
                     :href="`${baseUrl}/storage/system/ordersd.xls`"
                     target="_blank"
                     :underline="false">
              <el-button type="warning"
                         style="margin-left: 10px;vertical-align: initial;">
                下载刷单模板
              </el-button>
            </el-link>
          </el-upload>
        </el-col>
      </el-row>
    </template>

    <el-tabs v-model="activeName"
             class="table-header ba-scroll-style"
             @tab-click="handleStatus"
             type="border-card">
      <el-tab-pane label="全部"
                   name=""></el-tab-pane>
      <el-tab-pane label="等待发货"
                   name="AWAITING_SHIPMENT"></el-tab-pane>
      <el-tab-pane label="等待揽收"
                   name="AWAITING_COLLECTION"></el-tab-pane>
      <el-tab-pane label="运输中"
                   name="IN_TRANSIT"></el-tab-pane>
      <el-tab-pane label="已交付"
                   name="DELIVERED"></el-tab-pane>
      <el-tab-pane label="已完成"
                   name="COMPLETED"></el-tab-pane>
      <el-tab-pane label="已取消"
                   name="CANCELLED"></el-tab-pane>
      <el-tab-pane label="TK面单"
                   name="AWAITING_COLLECTION_TIKTOK"></el-tab-pane>
    </el-tabs>
    <!-- 表格 -->
    <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
    <Table>
      <!-- <template #shippingDocuments>
        <el-table-column  prop="shipping_documents" label="面单链接">
          <el-tooltip placement="top">
            <template #content>{{shipping_documents}}</template>
            <el-button>按钮</el-button>
          </el-tooltip>
        </el-table-column>
      </template> -->
    </Table>

    <!-- 表单 -->
    <!-- <PopupForm /> -->
  </div>
</template>


<script setup lang="ts">
import tablecol from './tablecol.vue'
import { markRaw, onBeforeMount, provide, reactive, ref } from 'vue'
import baTableClass from '/@/utils/baTable'
import PopupForm from './popupForm.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi, fileDownload } from '/@/api/common'
import { useAdminInfo } from '/@/stores/adminInfo'
import { useI18n } from 'vue-i18n'
import {ElMessage , type TabsPaneContext, ElMessageBox} from 'element-plus'
import { fileUpload, automaticShipping, mandatoryShipping, processedShunfeng, exportExcel, getWareHouseList, getGoldenByWarehouse } from '/@/api/backend/order/order'
import Cookies from 'js-cookie'
import { getShopList } from '/@/api/backend/common'
import { getUrl } from '/@/utils/axios'

defineOptions({
    name: 'order/order',
})

const { t } = useI18n()
const baseUrl = getUrl()
const adminInfo = useAdminInfo()
const activeName = ref('')
const shop_arr = ref([] as any[])
const state: {
    overseas_warehouse:string | number,
    overseas_warehouse_arr: Array<any>,
    golden_ant:string | number,
    golden_ant_channel: Array<any>,
    buttonLoading: boolean
} = reactive({
    overseas_warehouse:'',
    overseas_warehouse_arr: [],
    golden_ant: '',
    golden_ant_channel: [],
    buttonLoading: false,
})
type keymaps = {
    [key: string]: string | number
}
const warehouse_sel:keymaps = {}
const optButtons = defaultOptButtons(['edit', 'delete'])
optButtons[1].display = (row) => {
    return row.id != adminInfo.id
}


const baTable = new baTableClass(
    new baTableApi('/order/order/'),
    {
        column: [
            { type: 'selection', align: 'center', operator: false },
            // { label: t('order.order.order_id'), prop: 'order_id', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
            {
                label: '店铺',
                prop:  'shop_id',
                operator: 'LIKE', 
                comSearchRender:'slot',
                comSearchSlotName: 'shop',
                show: false
            },
            {   
                label: '店铺', 
                prop: 'shop_name', 
                align: 'center',
                operator: false
            },
            {
                label: t('order.order.order_id'),
                prop:  'order_id',
                operator: 'LIKE', 
                comSearchRender:'slot',
                comSearchSlotName: 'orderId'
            },
            { label: t('order.order.sku_info'), prop: 'skus_info', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
            { 
                label: t('order.order.status'), 
                prop: 'status', 
                align: 'center', 
                render: 'tag',
                replaceValue: { 
                    'AWAITING_SHIPMENT': t('order.order.AWAITING_SHIPMENT'), 
                    'AWAITING_COLLECTION': t('order.order.AWAITING_COLLECTION'),
                    'IN_TRANSIT': t('order.order.IN_TRANSIT'),
                    'DELIVERED': t('order.order.DELIVERED'),
                    'CANCELLED': t('order.order.CANCELLED'),
                    'AWAITING_COLLECTION_TIKTOK': 'TK面单',
                    'AWAITING_COLLECTION_TIKTOK_Complete': '已强制发货',
                    'AWAITING_COLLECTION_SHUNFENG': '顺丰TK面单',
                    'COMPLETED': '已完成',
                    'ON_HOLD': '暂停中',
                    'UNPAID': '未支付'
                },
                operator: false,//是否显示搜索
            },
            {
                label: '是否刷单',
                prop: 'brush_status',
                align: 'center',
                comSearchRender: 'remoteSelect',
                remote: {
                    pk: 'brush_status',
                    field: 'brush_status_value',
                    remoteUrl: '/order/order/getBrushlist',
                    params: { select: true },
                },
                show: false
            },
            { label: t('order.order.tracking_number'), prop: 'tracking_number', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query')  },
            { label: t('order.order.buyer_name'), prop: 'name', align: 'center', operator: false, operatorPlaceholder: t('Fuzzy query') },
            { label: t('order.order.buyer_phone'), prop: 'phone_number', align: 'center', operator: false, operatorPlaceholder: t('Fuzzy query') },
            {
                label: '仓库',
                prop: 'warehouse_name',
                align: 'center',
                render: 'tag',
                operator: false
            },
            { label: '创建时间(美国)', prop: 'createtime', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
            {
                label: '仓库',
                prop: 'warehouse_id',
                align: 'center',
                comSearchRender: 'select',
                replaceValue: warehouse_sel,
                show: false
            },
            // {
            //     label: '面单运费',
            //     prop: 'shipping_price',
            //     align: 'center', 
            //     operator: false,
            //     width: 120
            // },
            { 
                label: t('order.order.shipping_type'), 
                prop: 'shipping_type', 
                align: 'center', 
                render: 'tag',
                replaceValue: { 'SELLER': 'SELLER', 'TIKTOK': 'TIKTOK'},
                operator: true,//是否显示搜索
                show: true,//是否显示
            },
            {
                label: '面单链接', prop: 'shipping_documents', render: 'customRender', customRender: markRaw(tablecol) , operator: false, align: 'center', 
            },
            {
                label: '订单类型',
                prop: 'brush_status',
                operator: false,
                render: 'tag',
                align: 'center', 
            },
            {
                label: '网红订单',
                prop: 'free_status',
                operator: 'LIKE',
                render: 'tag',
                replaceValue: { 1: '否', 2: '是'},
                align: 'center',
            }
            // {
            //     label: '面单链接',
            //     prop: 'is_shipping_documents',
            //     operator: 'LIKE',
            //     render: 'tag',
            //     replaceValue: { 1: '有', 2: '无'},
            //     align: 'center',
            //     show: false
            // }
        ],
        dblClickNotEditColumn: ['all']
    },
    {
        defaultItems: {
            status: '1',
        }
    }
)

provide('baTable', baTable)

baTable.mount()
baTable.getIndex()

const handleStatus = (tab: TabsPaneContext) => {
    // baTable.filter = {'status': tab.props.name}
    baTable.comSearch.form['status'] = tab.props.name
    const comSearchData: Array<any> = baTable.table.filter?.search || [];
    comSearchData.push({
        field: "status",
        val: tab.props.name,
        operator: "",
        render: "",
    })
    baTable.onTableAction('com-search', comSearchData)
}

//上传刷单文件
const onBrushOrderUpload = (file: any) => {
    let fd = new FormData()
    fd.append('file', file.raw)
    fileUpload(fd).then((res) => {
        if (res.code == 200) {
            ElMessage ({
                type: 'success',
                message: res.msg,
            })
        } else {
            ElMessage ({
                type: 'error',
                message: '刷单上传失败',
            })
        }
    })
}

const automaticShippingOperate = () => {
    let ids = baTable.getSelectionIds()
    if (!ids.length) {
        ElMessage ({
            type: 'error',
            message: '请选择订单',
        })
        return
    }

    const params = { ids: ids, warehouse_id: state.overseas_warehouse, golden_ant: state.golden_ant}
    automaticShipping('post', params).then((res) => {
        baTable.toggleForm('')
        baTable.onTableHeaderAction('refresh', {})
    })
}

const mandatoryShippingOperate = () => {
    let ids = baTable.getSelectionIds()
    if (!ids.length) {
        ElMessage ({
            type: 'error',
            message: '请选择订单'
        })
        return
    }

    const params = { ids: ids, warehouse_id: state.overseas_warehouse, golden_ant: state.golden_ant}
    mandatoryShipping('post', params).then((res) => {
        baTable.toggleForm('')
        baTable.onTableHeaderAction('refresh', {})
    })
}

const processedShunfengOperate = () => {
    let ids = baTable.getSelectionIds()
    if (!ids.length) {
        ElMessage ({
            type: 'error',
            message: '请选择订单',
        })
        return
    }

    // console.log(99999, ids);
    // return
    const params = { ids: ids}
    processedShunfeng('post', params).then((res) => {
        baTable.onTableHeaderAction('refresh', {})
    })
}

const exportExcelOperate = () => {
    state.buttonLoading = true
    baTable.table.loading = true
    ElMessageBox.confirm(
        '是否确认导出所有数据项?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        type keymaps = {
            [key: string]: string | number
        }
        const obj:keymaps = {}
        baTable.table.filter?.search!.forEach(v => {
            obj[v.field] = v.val
        }) || []
        exportExcel('post', obj).then(response => {
            fileDownload(response, Cookies.get('filename') || 'file.xlsx')
        }).catch(err => {
            state.buttonLoading = false
            baTable.table.loading = false
        }).finally(() => { 
            state.buttonLoading = false
            baTable.table.loading = false
        })
    }).catch(() => {
        state.buttonLoading = false
        baTable.table.loading = false
    })
}

const getSummaries = (param:any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column:any, index:any) => {
    const key = column.columnKey
    switch(key){
        case 'shop_name':
            sums[index] = `总计: ${baTable.table.extend?.total_shipping_num} 条`
            break
        case 'shipping_price':
            sums[index] = `${baTable.table.extend?.total_shipping_price} USD`
            break
        default:
            sums[index] = ''
    }
  })
  return sums
}

const getOverseasWarehouseArr = () => {
    return getWareHouseList().then(res => {
        if(res.data && res.data.length) {
            state.overseas_warehouse_arr = res.data.map((v: any) => {
                warehouse_sel[v.warehouse_id] = v.warehouse_name
                return {
                    label: v.warehouse_name,
                    value: v.warehouse_id
                }
            })
            state.overseas_warehouse = state.overseas_warehouse_arr[0].value
        } else {
            state.overseas_warehouse = ''
            state.overseas_warehouse_arr = []
        }
    })
}

const overseasWarehouseChange = () => {
    getGoldenAntChannel()
}

const getGoldenAntChannel = () => {
    getGoldenByWarehouse({ warehouse_id: state.overseas_warehouse }).then(res => {
         if(res.data && res.data.length) {
            state.golden_ant_channel = res.data.map((v: any) => {
                return {
                    label: v.golden_ant_name,
                    value: v.golden_ant
                }
            })
            state.golden_ant = state.golden_ant_channel[0].value
        } else { 
            state.golden_ant = ''
            state.golden_ant_channel = []
        }
    })
}

const getShopArr = () => {
    getShopList().then(res => {
        if(res.data && res.data.list.length) {
            shop_arr.value = res.data.list
        }
    })
}

onBeforeMount(async () => {
    getShopArr()
    await getOverseasWarehouseArr()
    getGoldenAntChannel()
})

</script>

<style scoped lang="scss"></style>
